import router from './index'

const whiteList = ['/login', '/register']

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (token) {
    if (to.path === '/login' || to.path === '/register') {
      next('/')
    } else {
      // 检查页面权限
      if (to.meta.permission) {
        // 从localStorage获取用户信息
        const userInfoStr = localStorage.getItem('userInfo')
        if (!userInfoStr) {
          next('/login')
          return
        }
        
        try {
          const userInfo = JSON.parse(userInfoStr)
          const userType = userInfo.userType
          
          // 权限检查逻辑
          const hasPermission = (permission) => {
            const permissions = {
              'user:manage': userType === 1,
              'book:manage': userType === 1,
              'borrow:manage': userType === 1,
              'book:borrow': true, // 所有用户都可以借书
              'dashboard:view': true // 所有用户都可以查看首页
            }
            return permissions[permission] || false
          }
          
          if (!hasPermission(to.meta.permission)) {
            // 没有权限，重定向到首页
            next('/dashboard')
            return
          }
        } catch (error) {
          console.error('解析用户信息失败:', error)
          next('/login')
          return
        }
      }
      
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
}) 